package com.mmo.cq.game.server;

import com.mmo.cq.game.server.bean.server.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wxd.agent.loader.ClassDirLoader;
import org.wxd.agent.loader.JavaCoderCompile;
import org.wxd.batis.mongodb.MongoDataHelper;
import org.wxd.ioc.Ioc;
import org.wxd.ioc.IocConfig;
import org.wxd.net.message.MessageService;
import org.wxd.system.ClassUtil;
import org.wxd.system.JvmUtil;

import java.io.File;
import java.util.List;

public class AppMain {

    public static void main(String[] args) {
        try {
            init();
            initScript();
            Ioc.start(true, 1, "传奇", "测试版");
        } catch (Throwable throwable) {
            Logger logger = LoggerFactory.getLogger("root");
            logger.error("启动异常", throwable);
            System.exit(1);
        }
    }

    public static void init() throws Exception {

        JvmUtil.setLogbackConfig();
        IocConfig iocConfig = new IocConfig();
        iocConfig.bind(ServerConfig.class, ServerConfig.getInstance());
        Ioc.initBoot(iocConfig, AppMain.class);
        MongoDataHelper bean = Ioc.getBean(MongoDataHelper.class);
        bean.checkDataBase("com.mmo.cq.game.server.bean");

    }

    public static void initScript() throws Exception {
        File file = new File("./script.jar");
        ClassDirLoader classDirLoader;
        if (file.exists()) {
            classDirLoader = ClassDirLoader.bootLib(AppMain.class.getClassLoader(), file.getPath());
        } else {
            classDirLoader = new JavaCoderCompile()
                    .parentClassLoader(AppMain.class.getClassLoader())
                    .compilerJava("com.mmo.cq.game-server-script/src/main/java")
                    .builderClassLoader();
        }
        initScript(classDirLoader);
    }

    public static void initScript(ClassLoader classLoader) {
        MessageService.loadMessageId_HashCode(classLoader, true, "com.mmo.cq.game.script.proto.login.message");
        List<Class> scripts = ClassUtil.getClasses(classLoader, "com.mmo.cq.game.script");
        Ioc.iocInitBean(scripts);
    }

}